#pragma once

#include <iostream>
#include <string>
#include <pthread.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include "Log.hpp"

#define PORT 8081

static const int BACKLOG = 5;

class TcpServer
{
private:
    // 单例模式
    TcpServer(int _port = PORT)
        :port(_port),listen_sock(-1)
    {}
    TcpServer(const TcpServer& s) = delete;
public:
    ~TcpServer()
    {}
public:
    static TcpServer* GetInstance(int port)
    {
        static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
        if(svr == nullptr)
        {
            pthread_mutex_lock(&lock);
            if(svr == nullptr)  // 为什么要写第二遍？问题1
            {
                svr = new TcpServer(port);
                svr->InitTcpServer();
            }
            pthread_mutex_unlock(&lock);
        }
        return svr;
    }
    // 获取套接字
    int Sock()
    {
        return listen_sock;
    }
private:
    void InitTcpServer()
    {
        Socket();
        Bind();
        Listen();
        LOG(Info, "tcp_server init ... success");
    }
    // 创建套接字
    void Socket()
    {
        listen_sock = socket(AF_INET, SOCK_STREAM, 0);
        if(listen_sock < 0)
        {
            exit(1);
            LOG(Fatal, "create socket fail");
        }
        int opt = 1;
        setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
        LOG(Info, "create socket success");
    }
    // 绑定套接字
    void Bind()
    {
        struct sockaddr_in local;
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;
        if(bind(listen_sock, (struct sockaddr*)&local, sizeof(local)) < 0)
        {
            exit(2);
            LOG(Fatal, "bind socket fail");

        }
        LOG(Info, "bind socket success");
    }
    // 监听套接字
    void Listen()
    {
        if(listen(listen_sock, BACKLOG) < 0)
        {
            LOG(Fatal, "listen socket fail");
            exit(3);
        }
        LOG(Info, "listen socket success");
    }


private:
    int port;
    int listen_sock;

    // 设置成单例模式
    static TcpServer* svr;
};

TcpServer* TcpServer::svr = nullptr;